<template>
  <div class="app-container">
    <!-- 头部区域 -->
    <div class="app-header">
      <div class="header-left">
        <div class="logo" @click="handleLogoClick">
          <h1>环境管理平台</h1>
        </div>
      </div>
      
      <div class="header-right">
        <div class="admin-status" v-if="authState.isAdmin">
          <a-tag color="green">管理员模式</a-tag>
          <a-button type="link" @click="logout">退出登录</a-button>
        </div>
        
        <a-button 
          type="primary" 
          @click="refreshData"
          :loading="loading"
          :icon="h(ReloadOutlined)"
        >
          刷新
        </a-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-input-search
            v-model:value="filterState.searchKeyword"
            placeholder="搜索项目名称或域名..."
            @search="onSearch"
            @input="onSearchInput"
            size="large"
          />
        </a-col>
        
        <a-col :span="6">
          <a-select
            v-model:value="filterState.selectedGroupIds"
            mode="multiple"
            placeholder="选择项目分组"
            style="width: 100%"
            size="large"
            @change="onGroupFilter"
          >
            <a-select-option 
              v-for="group in groups" 
              :key="group.id" 
              :value="group.id"
            >
              {{ group.name }}
            </a-select-option>
          </a-select>
        </a-col>
        
        <a-col :span="2">
          <a-button 
            v-if="authState.isAdmin"
            type="dashed" 
            size="large"
            @click="showCreateGroup"
            :icon="h(PlusOutlined)"
            style="width: 100%"
            title="创建新分组"
          >
            分组
          </a-button>
        </a-col>
        
        <a-col :span="4">
          <a-button 
            v-if="authState.isAdmin"
            type="primary" 
            size="large"
            @click="showCreateProject"
            :icon="h(PlusOutlined)"
            style="width: 100%"
          >
            新建项目
          </a-button>
        </a-col>
      </a-row>
    </div>

    <!-- 项目列表区域 -->
    <div class="projects-section">
      <a-spin :spinning="loading">
        <div v-if="filteredProjects.length === 0" class="empty-state">
          <a-empty 
            :description="hasSearchFilter ? '没有找到匹配的项目' : '暂无项目数据'"
          >
            <a-button 
              v-if="authState.isAdmin && !hasSearchFilter"
              type="primary" 
              @click="showCreateProject"
            >
              创建第一个项目
            </a-button>
          </a-empty>
        </div>
        
        <div v-else class="projects-grid">
          <div v-for="project in filteredProjects" :key="project.id" class="project-item">
            <ProjectCard
              :project="project"
              :group="getGroupById(project.groupId)"
              :is-admin="authState.isAdmin"
              @edit="onEditProject"
              @delete="onDeleteProject(project.id)"
              @refresh="refreshData"
              @environmentChange="onEnvironmentChange"
            />
          </div>
        </div>
      </a-spin>
    </div>

    <!-- 项目表单弹窗 -->
    <ProjectForm
      v-model:visible="projectFormVisible"
      :groups="groups"
      :edit-project="editingProject"
      @success="onProjectFormSuccess"
    />

    <!-- 分组创建弹窗 -->
    <a-modal
      v-model:open="groupFormVisible"
      title="创建新分组"
      :footer="null"
      width="400px"
    >
      <a-form
        ref="groupFormRef"
        :model="groupForm"
        layout="vertical"
        @finish="onGroupFormSuccess"
      >
        <a-form-item
          label="分组名称"
          name="name"
          :rules="[{ required: true, message: '请输入分组名称' }]"
        >
          <a-input v-model:value="groupForm.name" placeholder="请输入分组名称" />
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit"
            :loading="groupLoading"
            style="width: 100%"
          >
            创建分组
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 登录弹窗 -->
    <a-modal
      v-model:open="loginModalVisible"
      title="管理员登录"
      :footer="null"
      width="400px"
    >
      <a-form
        ref="loginFormRef"
        :model="loginForm"
        layout="vertical"
        @finish="onLogin"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="loginForm.username" placeholder="用户名" />
        </a-form-item>
        
        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model:value="loginForm.password" placeholder="密码" />
        </a-form-item>
        
        <a-form-item>
          <a-button 
            type="primary" 
            html-type="submit"
            :loading="loginLoading"
            style="width: 100%"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h, nextTick, watch } from 'vue';
import { message } from 'ant-design-vue';
import { ReloadOutlined, PlusOutlined } from '@ant-design/icons-vue';
import ProjectCard from '@/components/ProjectCard.vue';
import ProjectForm from '@/components/ProjectForm.vue';
import type { Project, ProjectGroup, FilterState, AuthState } from '@/types';
import { projectApi, groupApi } from '@/api';
import { authManager } from '@/utils/auth';
import { storageManager } from '@/utils/storage';

// 响应式数据
const loading = ref(false);
const loginLoading = ref(false);
const projects = ref<Project[]>([]);
const groups = ref<ProjectGroup[]>([]);

// 筛选状态
const filterState = reactive<FilterState>({
  searchKeyword: '',
  selectedGroupIds: [],
});

// 权限状态
const authState = reactive<AuthState>({
  isAdmin: false,
  loginClickCount: 0,
});

// 弹窗状态
const projectFormVisible = ref(false);
const groupFormVisible = ref(false);
const loginModalVisible = ref(false);
const editingProject = ref<Project | null>(null);

// 分组表单
const groupFormRef = ref();
const groupForm = reactive({
  name: '',
});

// 分组相关状态
const groupLoading = ref(false);

// 登录表单
const loginFormRef = ref();
const loginForm = reactive({
  username: '',
  password: '',
});

// 计算属性
const hasSearchFilter = computed(() => {
  return filterState.searchKeyword.trim() || filterState.selectedGroupIds.length > 0;
});

const filteredProjects = computed(() => {
  let result = [...projects.value];

  // 按关键词搜索
  if (filterState.searchKeyword.trim()) {
    const keyword = filterState.searchKeyword.toLowerCase();
    result = result.filter(project => {
      // 搜索项目名称
      if (project.name.toLowerCase().includes(keyword)) {
        return true;
      }
      
      // 搜索域名
      return project.environments.some(env => 
        env.hosts.some(host => host.toLowerCase().includes(keyword))
      );
    });
  }

  // 按分组筛选
  if (filterState.selectedGroupIds.length > 0) {
    result = result.filter(project => 
      filterState.selectedGroupIds.includes(project.groupId)
    );
  }

  return result;
});

const updateWhistleRule = async () => {
  const activeIds = storageManager.getActiveEnvironments();
  const environments = projects.value.map(project => project.environments).flat();
  const rules = environments.filter(env => activeIds.includes(env.id)).map(env => env.hosts).flat();
  await projectApi.updateRules(rules);
};

// 环境变化处理（配合互斥激活系统）
const onEnvironmentChange = async (envId: string, checked: boolean, envType: 'development'|'test'|'preview'|'production'|'custom') => {
  // 由于存储管理器已经处理了互斥逻辑，这里只需要同步UI状态
  
  // 1) 同步到页面本地状态（切换文案）
  const all = projects.value.flatMap(p => p.environments);
  const activeSet = new Set(storageManager.getActiveEnvironments());
  all.forEach(env => {
    env.isActive = activeSet.has(env.id);
  });

  // 2) 重新计算并下发规则
  await updateWhistleRule();
  
  // 3) 显示环境切换提示
  if (checked) {
    const envName = all.find(env => env.id === envId)?.name || '未知环境';
    const envTypeName = getEnvironmentTypeName(envType);
    message.success(`${envTypeName} "${envName}" 已激活`);
  }
};

// 获取环境类型名称的辅助函数
const getEnvironmentTypeName = (envType: string): string => {
  const typeNames: Record<string, string> = {
    development: '开发环境',
    test: '测试环境',
    preview: '预发布环境',
    production: '正式环境',
    custom: '自定义环境',
  };
  return typeNames[envType] || '未知环境';
};

// 根据分组ID获取分组信息
const getGroupById = (groupId: string) => {
  return groups.value.find(group => group.id === groupId);
};

// 初始化数据
const initData = async () => {
  loading.value = true;
  
  try {
    await loadProjects()
    await updateWhistleRule()
  } catch (error: any) {
    message.error(error.message || '数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 加载项目数据
const loadProjects = async () => {
  try {
    const response = await projectApi.getAll();
    if (response.success && response.data) {
      projects.value = response.data.projects;
      groups.value = response.data.projectGroups;
    }
  } catch (error: any) {
    console.error('加载项目失败:', error);
    throw error;
  }
};

// 刷新数据
const refreshData = async () => {
  await loadProjects();
  message.success('数据刷新成功');
};

// 显示创建分组弹窗
const showCreateGroup = () => {
  groupFormVisible.value = true;
  groupForm.name = '';
  nextTick(() => {
    groupFormRef.value?.clearValidate();
  });
};

// 分组表单提交成功
const onGroupFormSuccess = async (values: any) => {
  try {
    groupLoading.value = true;
    const response = await groupApi.create(values);
    if (response.success) {
      message.success('分组创建成功');
      groupFormVisible.value = false;
      await loadProjects(); // 重新加载数据
    } else {
      message.error(response.message || '分组创建失败');
    }
  } catch (error: any) {
    message.error(error.message || '分组创建失败');
  } finally {
    groupLoading.value = false;
  }
};

// Logo点击处理
const handleLogoClick = () => {
  const shouldShowLogin = authManager.handleLogoClick();
  authState.loginClickCount = authManager.getLoginClickCount();
  
  if (shouldShowLogin) {
    loginModalVisible.value = true;
    // 重置登录表单
    loginForm.username = '';
    loginForm.password = '';
    nextTick(() => {
      loginFormRef.value?.clearValidate();
    });
  }
};

// 管理员登录
const onLogin = async () => {
  try {
    loginLoading.value = true;
    
    const success = authManager.login(loginForm.username, loginForm.password);
    if (success) {
      authState.isAdmin = true;
      loginModalVisible.value = false;
      message.success('登录成功');
    } else {
      message.error('用户名或密码错误');
    }
  } catch (error) {
    message.error('登录失败');
  } finally {
    loginLoading.value = false;
  }
};

// 退出登录
const logout = () => {
  authManager.logout();
  authState.isAdmin = false;
  message.success('已退出登录');
};

// 搜索处理
const onSearch = () => {
  saveFilterState();
};

const onSearchInput = () => {
  saveFilterState();
};

// 分组筛选处理
const onGroupFilter = () => {
  saveFilterState();
};

// 保存筛选状态
const saveFilterState = () => {
  storageManager.saveFilterState(filterState);
};

// 加载筛选状态
const loadFilterState = () => {
  const savedState = storageManager.getFilterState();
  Object.assign(filterState, savedState);
};

// 显示创建项目弹窗
const showCreateProject = () => {
  editingProject.value = null;
  projectFormVisible.value = true;
};

// 编辑项目
const onEditProject = (projectId: string) => {
  const project = projects.value.find(p => p.id === projectId);
  if (project) {
    editingProject.value = project;
    projectFormVisible.value = true;
  }
};

// 删除项目
const onDeleteProject = (projectId: string) => {
  projectApi.delete(projectId);
  refreshData();
};

// 项目表单操作成功
const onProjectFormSuccess = () => {
  refreshData();
};

// 监听筛选状态变化，自动保存
watch(filterState, () => {
  saveFilterState();
}, { deep: true });

// 组件挂载
onMounted(() => {
  // 加载权限状态
  authState.isAdmin = authManager.getIsAdmin();
  authState.loginClickCount = authManager.getLoginClickCount();
  
  // 加载筛选状态
  loadFilterState();
  
  // 初始化数据
  initData();
});
</script>

<style scoped>
.app-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 24px;
  padding-top: 0;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  cursor: pointer;
  user-select: none;
}

.logo h1 {
  margin: 0;
  color: #1890ff;
  font-size: 24px;
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.admin-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-filter-section {
  margin-bottom: 24px;
  margin-top: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.projects-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  min-height: 400px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  width: 100%;
}

.project-item {
  transition: transform 0.2s ease;
  margin-bottom: 20px;
  width: 100%;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.project-item:hover {
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }
  
  .app-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-right {
    justify-content: space-between;
  }
  
  .projects-grid {
    grid-template-columns: 1fr;
  }
  
  .search-filter-section .ant-row {
    flex-direction: column;
  }
  
  .search-filter-section .ant-col {
    width: 100% !important;
    margin-bottom: 12px;
  }
}
</style>
